package com.sptpc.stu.controller.upload;

import com.sptpc.stu.common.response.JSONResponse;
import com.sptpc.stu.common.response.impl.Status;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;

@Slf4j
@RestController
@RequestMapping("/upload")
public class UploadController {

    public static final String SAVE_PATH = "C:/upload";
    public static final String AVATAR_PATH = "/pic";

    @RequestMapping(value = "/" , method = RequestMethod.POST)
    public JSONResponse upload(MultipartFile file) {

        if (file!=null && !file.isEmpty()) {
            try {
                String fileName = System.currentTimeMillis() + getFileExtension(file.getOriginalFilename());
                String filePath = SAVE_PATH + AVATAR_PATH + fileName;
                File destFile = new File(filePath);
                destFile.getParentFile().mkdirs();
                file.transferTo(destFile);
                return JSONResponse.ofSuccess(AVATAR_PATH + fileName);
            } catch (IOException e) {
                log.error(e.getMessage());
                return JSONResponse.ofStatus(Status.UPLOAD_ERROR);
            }
        } else {
            return JSONResponse.ofStatus(Status.UPLOAD_ERROR);
        }

    }

    private String getFileExtension(String fileName) {
        // xxxxx.xxx.jpg
        int index = fileName.lastIndexOf(".");
        return fileName.substring(index);
    }

}
